﻿using Lego.Ev3.Core;
using Lego.Ev3.Phone;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Enough.Lego.Mindstorms.WP.Model
{
    public class BaseController
    {
        private ICommunication _communicationInterface;
        public ICommunication CommunicationInterface
        {
            get { return _communicationInterface; }
            set
            {
                _communicationInterface = value;
                if (IsConnected)
                {
                    Brick.Disconnect();
                    IsConnected = false;
                }
            }
        }

        public bool IsConnected { get; private set; }
        public Brick Brick { get; private set; }


        public async Task EnsureIsConnectedAsync()
        {
            if (!IsConnected)
            {
                await ConnectAsync();
            }
        }

        public async Task ConnectAsync()
        {
            ICommunication comm = CommunicationInterface;
            if (comm == null)
            {
                comm = new BluetoothCommunication();
            }
            Brick brick = new Brick(comm);
            Brick = brick;
            await brick.ConnectAsync();
            IsConnected = true;
        }

        public void DisconnectBrick()
        {
            Brick.Disconnect();
            IsConnected = false;
        }
    }
}
